<?php
/**
 * 微信关键字管理
 * User: Administrator
 * Date: 2019/11/27 0027
 * Time: 13:32
 */

namespace app\admin\controller;


use service\DataService;
use think\Db;

class WechatKeys extends BasicAdmin{

    /**
     * 指定当前数据表
     * @var string
     */
    public $table = 'WechatKeys';

    /**
     * 显示关键字列表
     */
    public function index(){
        if($this->request->isPost()){
            $param = $this->request->param();
            $db = Db::name($this->table)->order('id '.$param['order'])->where('keys', 'not in', ['subscribe', 'default']);
            return parent::_list($db,$param);
        }
        $this->title = '微信管理 > 微信关键字';
        return $this->fetch('wechat/keys/index', ['title' => $this->title]);
    }

    /**
     * 列表数据处理
     * @param array $data
     */
    protected function _index_data_filter(&$data)
    {
        $types = [
            'keys'  => '关键字', 'image' => '图片', 'news' => '图文',
            'music' => '音乐', 'text' => '文字', 'video' => '视频', 'voice' => '语音'
        ];
        $wechat = load_wechat('Extends');
        foreach ($data as &$vo) {
            $result = $wechat->getQRCode($vo['keys'], 1);
            $vo['qrc'] = $wechat->getQRUrl($result['ticket']);
            $vo['type'] = isset($types[$vo['type']]) ? $types[$vo['type']] : $vo['type'];
        }
    }


    /**
     * 添加关键字
     * @return string
     */
    public function add(){
        $this->title = '添加关键字规则';
        return $this->_form($this->table, 'wechat/keys/form');
    }

    public function edit(){
        $this->title = '编辑关键字规则';
        return $this->_form($this->table, 'wechat/keys/form');
    }

    /**
     * 表单处理
     * @param $data
     */
    protected function _form_filter($data)
    {
        if ($this->request->isPost() && isset($data['keys'])) {
            $db = Db::name($this->table)->where('keys', $data['keys']);
            !empty($data['id']) && $db->where('id', 'neq', $data['id']);
            $db->count() > 0 && $this->error('关键字已经存在，请使用其它关键字！');
        }
    }

    /**
     * 删除关键字
     */
    public function del()
    {
        if (DataService::update($this->table)) {
            $this->success("关键字删除成功！", '');
        }
        $this->error("关键字删除失败，请稍候再试！");
    }

    /**
     * 关键字禁用
     */
    public function forbid()
    {
        if (DataService::update($this->table)) {
            $this->success("关键字禁用成功！", '',['status'=>2]);
        }
        $this->error("关键字禁用失败，请稍候再试！");
    }

    /**
     * 关键字启用
     */
    public function resume()
    {
        if (DataService::update($this->table)) {
            $this->success("关键字启用成功！", '',['status'=>1]);
        }
        $this->error("关键字启用失败，请稍候再试！");
    }



}